import { ref, nextTick, isReactive } from 'vue'
import { http } from '@/utils/http'

export default function (api, queryParam, callback) {
  const scrollTop = ref(-1)
  const loadStatus = ref('loading')
  const refreshStatus = ref(false) // 下拉刷新状态
  const pageNumber = ref(1) // 分页 number
  const dataSource = ref([]) // 数据源
  const allTotal = ref(0) //总条数
  const lastFetchId = ref(0)
  const hotUpdateFlag = ref(false) // 热更新

  // 下拉刷新(重置刷新)
  const resetRefresh = (pullDown = false) => {
    pageNumber.value = 1
    if (pullDown) {
      refreshStatus.value = true
    }
    allTotal.value = 0
    loadData(1)
  }
  // 上拉加载
  const reachBottom = () => {
    // nomore 直接返回
    if (loadStatus.value == 'nomore') return
    loadStatus.value = 'loading'
    loadData()
  }
  // 回到顶部
  const goTop = () => {
    scrollTop.value = -1
    nextTick(() => {
      scrollTop.value = 0
    })
  }
  // 热更新加载数据
  const fetchHotData = (page) => {
    // 获取当前最后最后一页的数据
    console.log(pageNumber.value)
    const currPage = page ? page - 1 : pageNumber.value - 1
    fetchData(currPage, (list) => {
      // 当前的数据源
      const source = dataSource.value
      // 遍历最后一页的数据，如果存在，则去除，不存在保留
      const filteredList = list.filter((item) => {
        const findItem = source.find((sourceItem) => sourceItem.id == item.id)
        return !findItem
      })
      // 补充新增的数据
      dataSource.value = [...dataSource.value, ...filteredList]
      // 正常获取下一页
      fetchData(page)
      // 更新热更新
      updateHotUpdateFlag(false)
    })
  }
  // 加载数据
  const fetchData = (page, fetchDataCallback) => {
    const tempQueryParam = isReactive(queryParam) ? queryParam : queryParam.value
    if (!page) {
      if (tempQueryParam.pageNumber) {
        page = tempQueryParam.pageNumber
        tempQueryParam.pageNumber = undefined
      }
    }
    var param = {
      pageSize: 10,
      ...tempQueryParam,
      pageNumber: page || pageNumber.value,
    }
    lastFetchId.value += 1
    const fetchId = lastFetchId.value
    // 调列表方法
    return new Promise((resolve, reject) => {
      http({
        method: 'POST',
        url: api,
        data: param,
      })
        .then((res) => {
          if (res.code == 200) {
            if (fetchId !== lastFetchId.value) {
              // 非顺序
              return
            }
            let { data, totalPage, total } = res.result
            if (fetchDataCallback && typeof fetchDataCallback === 'function') {
              fetchDataCallback(data)
            } else {
              pageNumber.value = param.pageNumber
              allTotal.value = total
              // 第一页list替换，否则追加
              if (pageNumber.value == 1) {
                dataSource.value = []
                nextTick(() => {
                  dataSource.value = data
                  loadStatus.value = 'loading'
                  callback && callback(dataSource.value, res.result)
                  // 到顶部
                  goTop()
                  refreshStatus.value = false

                  // 最后一条判断
                  if (pageNumber.value >= totalPage) {
                    loadStatus.value = 'nomore'
                  } else {
                    pageNumber.value++
                  }
                })
              } else {
                dataSource.value = [...dataSource.value, ...data]
                callback && callback(dataSource.value, res.result)
                // 最后一条判断
                if (pageNumber.value >= totalPage) {
                  loadStatus.value = 'nomore'
                } else {
                  pageNumber.value++
                }
              }
            }
          } else {
            uni.showToast({
              icon: 'none',
              title: res.message,
            })
          }
          resolve(dataSource.value)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 加载数据
  const loadData = (page) => {
    if (page == 1) hotUpdateFlag.value = false
    if (hotUpdateFlag.value) {
      fetchHotData(page)
    } else {
      return fetchData(page)
    }
  }

  // 更新热更新
  const updateHotUpdateFlag = (val) => {
    hotUpdateFlag.value = val
  }

  return {
    scrollTop,
    loadStatus,
    refreshStatus,
    dataSource,
    allTotal,
    resetRefresh,
    reachBottom,
    goTop,
    loadData,
    updateHotUpdateFlag,
  }
}
